<?php
/**
 * @orm tablename newsletters
 */
class NewsLetter extends DomArObject {
	
	/**
	 * @orm text
	 */
	public $title;
	/**
	 * @orm plugin DomArDateTime(now)
	 */
	public $datetime;
	/**
	 * @orm owns many NewsLetterItem inverse letter
	 */
	public $items;
	/**
	 * @orm char(255)
	 */
	public $template;
	
	const TEMPLATES_DIR = 'NewsLetters/';
	
	
	
	public function getNewView( $templateFileName = 'index.html' ) {
		return  new DomView( '/' . self::TEMPLATES_DIR . $this->template . '/'.$templateFileName );;
	}
	/**
	 * Renders newsletter
	 * @return String
	 */
	public function render( ) {
		
		$view = $this->getNewView();
		
		$view->item = $this;
		
		$html = '';
		foreach( $this->items->query()->orderBy('t.order')->commit() as $item ) {
			$html .= $item->render();	
		}
		$view->contents = $html;

		return $view->fetch();
	}
	
	public function getTemplates() {
		
		$path = DOM_TEMPLATES_DIR . self::TEMPLATES_DIR;
		$list = array();
		if ($handle = opendir( $path )) {
		    while( false !== ($file = readdir($handle)) ) {
		        if ($file != "." && $file != ".." && is_dir($path.$file) ) {
		        	$list[$file] = $file;
		        }
		    }
		    closedir($handle);
		}
		return $list;
	}
	
	public static function install( ) {
		NewsLetter::getTable()->update();
		NewsLetterItem_Basic::getTable()->update();
	}
	
}
?>